package com.travel.Service.impl;


import com.travel.Service.HotelSearchService;
import com.travel.pojo.Hotel;
import com.travel.repo.HotelRepository;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HotelSearchServiceImpl implements HotelSearchService {

    @Resource
    HotelRepository hotelRepository;

    @Resource
    private ElasticsearchOperations elasticsearchTemplate;


    @Override
    public Page<Hotel> search(String keyword, int pageNumber, int pageSize) {

        Query searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery(keyword, "name", "address"))
                .withPageable(PageRequest.of(pageNumber, pageSize))
                .build();

        SearchHits<Hotel> searchHits = elasticsearchTemplate.search(searchQuery, Hotel.class);
        List<Hotel> hotelList = searchHits.getSearchHits().stream()
                .map(SearchHit::getContent)
                .collect(Collectors.toList());

        return new PageImpl<>(hotelList, PageRequest.of(pageNumber, pageSize), searchHits.getTotalHits());

    }

}
